package server.main.utils.mainutils;

import com.mysql.cj.jdbc.Driver;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Map;

public class CreateTableUtils {


    /**
     *
     * @param table_name 所要建立的表的名字
     * @param key 是整个的表的属性
     * @param data_type 数据类型
     * @param data_length 数据长度
     * @param primarykey 主键
     * @param not_null 是否能为空，1为不为空，0为空。
     * @param auto_increase   是否自增，0非自增，1自增
     * @return 返回的是sql语句
     */
    public static String Get_sql(String table_name, String[] key, String[] data_type, String[] data_length, String[] primarykey, Integer[] not_null, Integer[] auto_increase){
        String str_sql = "create table" + " " + table_name + " (";//CREATE TABLE
        int i = 0;
        for(String eve_key:key){
            str_sql = str_sql + " " + eve_key + " " + data_type[i] + "(" + data_length[i] + ") ";
            if(not_null[i] == 1){
                str_sql = str_sql + "not null" ;
            }
            if(auto_increase[i] == 1)
                str_sql = str_sql + " auto_increment ,";//AUTO_INCREMENT
            else
                str_sql = str_sql + ",";

            i++;

        }
        int j = 1;
        str_sql = str_sql + " primary key(";//PRIMARY KEY (`id`)
        for(String pri_key:primarykey){
            if(j < primarykey.length)
                str_sql = str_sql + pri_key + ",";
            else
                str_sql = str_sql + pri_key;
            j++;
        }
        str_sql = str_sql + ") )";

        return str_sql;
    }

    /**
     * 实现建立数据库中的表
     * @param sql 建表的sql语句
     * @return
     * @throws Exception
     */

    public static boolean creat_table(String sql) throws Exception {

        boolean flag = true;
        String ymlpath = UrlUtils.GetResourcesUrl() + "application.yml";
        Map datasource = ymlUtils.getDatasource(ymlpath);
        DriverManager.registerDriver(new Driver());
        System.out.println(datasource.get("username"));
        String username = (String) datasource.get("username");
        String password = datasource.get("password").toString();
        String url = (String) datasource.get("url");
//        String url2 = "jdbc:mysql://localhost:3306/bloodtransfusionmanagement"
        Connection conn = null;
        Statement stat = null;
        //创建表test
        try{
            System.out.println(username+" " + password + " " + url);
            conn = DriverManager.getConnection(url, username, password);
            stat = conn.createStatement();

            stat.executeUpdate(sql);
        }catch (Exception e){
            flag = false;
            e.printStackTrace();
        }finally {
            stat.close();
            conn.close();

        }
        return flag;
    }

    public static void main(String[] args) throws Exception {
//        System.out.println(creat_table("1"));
    }
}
